package 力扣_中等题;

import java.util.List;

import static com.sun.xml.internal.ws.binding.FeatureListUtil.mergeList;

/**
 * @author 连安利
 * @version 1.0
 * @date 2021/3/23 14:59
 */
public class 重排链表 {
//    找链表中间节点加上链表反转
    public void reorderList(ListNode head) {
        if(head == null){
            return;
        }
        ListNode l1 = head;
//        找中间节点
        ListNode mid = findMid(head);

        ListNode l2 = mid.next;
//        通过中间节点切断链表
        mid.next = null;
//        反转后段链表
        l2 = reversalList(l2);
//        合并链表
        mergeList(l1,l2);

    }

    public ListNode findMid(ListNode head){
        ListNode slow = head;
        ListNode fast = head;
        while(fast.next != null && fast.next.next != null){
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }
    public ListNode reversalList(ListNode head){
        ListNode newNode = new ListNode(-1);
        ListNode temp ;
        ListNode cur = head;
        while (cur != null) {
            temp = cur.next;//保存下一个节点
            cur.next = newNode.next;//将当前节点的下一个节点指向新链表头节点的下一个节点
            newNode.next = cur;//新链表的头节点指向这个节点
            cur = temp;//从temp中获取到旧链表的位置
        }
        return newNode.next;
    }

    private void mergeList(ListNode l1, ListNode l2) {
        ListNode l1_tmp;
        ListNode l2_tmp;
        while (l1 != null && l2 != null) {
            l1_tmp = l1.next;
            l2_tmp = l2.next;

            l1.next = l2;
            l1 = l1_tmp;

            l2.next = l1;
            l2 = l2_tmp;
        }
    }
}
